/**
 * Created by Administrator on 2018-12-27.
 */
var widgetUtil={
    baseScript:"",
    loadPage:function(form,formSelects,laydate,layedit,widgetId,classFlag){
        //var url = this.switchPage(classFlag);
        $.getJSON(basePath+"/xdWidget/edit",{id:widgetId,classFlag:classFlag},function(rst){
            $("#xdWidget-attr-dom").load(rst.html,function(data){
                widgetUtil.baseScript = rst.baseScript;

                form.val("xdWidget-attr-form",{classFlag:classFlag})
                if(classFlag=="xd-select" && rst.data.serverFlag){
                    $('.layui-form-item-01').append($("#serverFlag-dom").html())
                    widgetUtil.initDataSource(form,"#dataSourceId",rst.data.dataSourceId)
                }
                form.val("xdWidget-attr-form",rst.data)

                $("#xdWidget-dom-view").html(rst.data.html||rst.baseScript)
                formSelects.render()
                form.render('checkbox');
                form.render('select');
                form.render('radio');
                if(classFlag == "xd-date"){
                    laydate.render({elem:".xd-date",type:rst.data.type,value: new Date(commonUtil.setDefaultDate(rst.data.defaultValue)),theme:rst.data.theme})
                }
            })
        })
    },
    createHtml:function(param){
        var classFlag = param.classFlag;
        var htmlDom = $(param.baseScript)
        var begin = '<div class="layui-inline">'
        var end = '</div>'
        var label = ''
        if(param.label){
            label = '<label class="layui-form-label">'+param.label+'</label>'
        }
        var domBegin = '<div class="layui-input-inline">'
        var domEnd = "</div>"
        htmlDom.attr("name",param.name);
        htmlDom.attr("id",param.name);
        htmlDom.attr("lay-verify",param.verify)

        switch (classFlag){
            case "xd-input":
                htmlDom.attr("placeholder",param.placeholder)
                htmlDom.attr("type",param.type)

                htmlDom.attr("readonly",!param.readable)
                htmlDom.attr("style",param.style);
                break;
            case "xd-select":
                htmlDom.attr("xm-select",param.name)
                htmlDom.attr("xm-select-show-count",1)
                if(param.maxCount != 0){
                    htmlDom.attr("xm-select-max",param.maxCount)
                }else{
                    htmlDom.removeAttr("xm-select-max")
                }
                if(param.radio){
                    htmlDom.attr("xm-select-radio",param.radio)
                }else{
                    htmlDom.removeAttr("xm-select-radio")
                }
                if(param.serverFlag){
                    htmlDom.html("")
                }else{
                    htmlDom.html(param.options)
                }

                if(param.width){
                    domBegin = '<div class="layui-input-inline" style="width:'+param.width+' " >'
                }

                htmlDom.attr("disabled",param.disabled)

                htmlDom.attr("xm-select-skin",param.skin);
                break;
            case "xd-date":
                htmlDom.attr("style",param.style);
                break;
        }
        var result = begin+label+domBegin+htmlDom.prop("outerHTML")+domEnd+end
        //console.log(result)
        return result
    },
    initDataSource:function(form,dom,value){
        $.getJSON(basePath+"/xdDataSource/all",function(rst){
            if(rst.code ==0){
                $(dom).html("<option value=''></option>")
                $.each(rst.data,function(i,item){
                    $(dom).append("<option value='"+item.ID+"'>"+item.SOURCE_NAME+"</option>")
                })
            }
            $(dom).val(value)
            form.render("select")
        })
    }
}


layui.config({
    base: basePath+'/layui/lay/modules/'
}).extend({
    formSelects: 'formSelects-v4'
}).use([ 'table','form','formSelects' ,'element','laydate','laytpl','layedit'], function() {
    var $ = layui.$;
    var form = layui.form;
    var formSelects = layui.formSelects;
    var layer = layui.layer;
    var table = layui.table;
    var element = layui.element;
    var laydate= layui.laydate;
    var laytpl = layui.laytpl;
    var layedit = layui.layedit;

    $("#widget-add").click(function(){
        layer.open({
            type:1,
            title:"<i class='layui-icon layui-icon-note'> 新增</i>",
            content: $("#xdWidget-add-dom").html(),
            area: ['400px', '300px'],
            end : function(){
                table.reload("xdWidget-tb")
                $("#xdWidget-attr-dom").html("属性区域")
                $("#xdWidget-dom-view").html("预览")
            },
            success:function(layero, index){
                formSelects.data('xdWidgetId', 'server', {
                    url: basePath+'/xdWidget/xdWidgets'
                });
            }
        })
    })

    $("#searchStr").bind('input propertychange', function() {
        table.reload("xdWidget-tb")
    });


    form.on("submit(xdWidget-add-form-bt)",function(d){
        //console.log(d)
        var param = d.field;
        $.getJSON(basePath+"/xdWidget/addXdWidget",param,function(data){
            if(data.code==0){
                layer.closeAll();
                table.reload("xdWidget-tb")
                $("#xdWidget-attr-dom").html("属性区域")
                $("#xdWidget-dom-view").html("预览")
            }else{
                layer.msg(data.msg)
            }
        })
        return false;
    })


    var tableOption = {
        elem: '#xdWidget-tb'
        ,url: basePath + '/xdWidget/listXdWidget'
        ,where:{searchStr:function(){return $("input[name='searchStr']").val()}}
        ,method:"post"
        ,toolbar:false
        ,title:"系统参数配置"
        ,defaultToolbar:false//['filter', 'print']
        ,cols: [[
            {title:"选择",fixed:'left', width:60,templet:function(d){
                return '<input type="radio" name="tb-radio" lay-filter="tb-radio"  value="'+d.ID+'" class-flag="'+ d.CLASS_FLAG+'" >'
            }},
            {field:'NAME', title: '名称',fixed:'left',sort:true,templet:function(d){
                var str = d.NAME
                if( d.LABEL){
                    str = d.NAME +"("+ d.LABEL+")"
                }
                return  str
            }}
            //,{field:'LABEL', title: '标签',sort:true}
            ,{field:'XD_WIDGET', title: '标签',sort:true }
            //,{field:'CREATOR', title: 'CREATOR',sort:true }
            ,{title: "操作", width:60,fixed:'right',templet:function(d){
                return '<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="delWidget">删除</a>'
            }}
        ]]
        ,page: {groups:3,layout:['prev', 'page', 'next','refresh']}
        ,height: 'full-130'
    }


    var tableDom = table.render(tableOption)
    var objId ;
    table.on("tool(xdWidget-tb)",function(obj) {
        var data = obj.data
        if(obj.event === 'delWidget'){//删除行
            var param = {classFlag:data.CLASS_FLAG,id:data.ID};
            layer.confirm("确定要删除该记录吗，此操作不能恢复!", {icon: 3, title:'提示'}, function (index) {
                    $.ajax(basePath+"/xdWidget/del",{
                        dataType:"json",
                        type:"post",
                        data:param,
                        success:function(rdata){
                            layer.msg(rdata.msg)
                            if(rdata.code == 0){
                                table.reload("xdWidget-tb")
                            }
                        }
                    });
                    layer.close(index);
                }
            )
        }
    })

    form.on('radio(tb-radio)', function(data){
        //console.log( data.elem ); //得到radio原始DOM对象
        //被点击的radio的value值
        //console.log(data.value,$(data.elem).attr("class-flag"));
        var id = data.value;
        var classFlag = $(data.elem).attr("class-flag")
        var divHeight = $('.xd-div-sample').height()
        var h1 = $('.xd-div-sample2').height()
        var h2 = $(".layui-footer").height()
        //console.log(divHeight,divHeight-43)
        $(".xd-div-set").css("height",divHeight-h1-22)
        widgetUtil.loadPage(form,formSelects,laydate,layedit,id,classFlag)

    });


    //更新classFlag对应widget
    form.on("submit(xdWidget-attr-form-bt)",function(obj){
        var param = obj.field
        param.baseScript = widgetUtil.baseScript
        param.html = widgetUtil.createHtml(param)
        //console.log(param)
        $.post(basePath+"/xdWidget/save",param,function(rst){
            if(rst.code==0){
                layer.msg(rst.msg)
                $("#xdWidget-dom-view").html(param.html)
                formSelects.render()
                form.render('checkbox');
                form.render('radio');
                laydate.render({elem:".xd-date"})
            }else{
                layer.msg("操作失败：控件名已存在")
            }
        },"json")
        return false;
    })


    form.on("submit(xdWidget-preview-form-bt)",function(obj){
        $("#xdWidget-dom-view").html("")
        var param = obj.field
        console.log(param)
        param.baseScript = widgetUtil.baseScript
        param.math_ =  Math.random();

        $("#xdWidget-dom-view").html(widgetUtil.createHtml(param))
        if(param.classFlag =="xd-select" ){

            if(param.serverFlag){
                formSelects.data(param.name, 'server', {//远程根据 keyword 查询
                    type:"post",
                    data:param,
                    searchUrl:basePath+"/xdWidgetSelect/selectView",
                    success: function(id, url, searchVal, result){           //使用远程方式的error回调
                        if(result.code !=0){
                            layer.alert(result.msg,{icon: 2})
                        }
                    }
                });
            }else{
                formSelects.render(param.name)
            }
        }

        form.render('checkbox');
        form.render('radio');
        //console.log(widgetUtil.setDefaultDate(param.defaultValue))
        laydate.render({elem:".xd-date",type:param.type,value: new Date(commonUtil.setDefaultDate(param.defaultValue)),theme:param.theme })
        return false;
    })

    form.on("submit(xdWidget-view-form-bt)",function(obj){
        var param = obj.field
        layer.msg("表单已提交")
        return false;
    })


    form.on('checkbox(serverFlag)', function(data){
        var checkFlag = data.elem.checked;
        //console.log(checkFlag)
        if(checkFlag){
            $('.layui-form-item-01').append($("#serverFlag-dom").html())
            widgetUtil.initDataSource(form,"#dataSourceId")
            form.render('checkbox')
        }else{
            $('.layui-form-item-01').children(".serverFlag-dom-add").remove()
        }
    });


    form.on('checkbox(radio)', function(data){
        var checkFlag = data.elem.checked;
        if(checkFlag){
            $("input[name=splitStr]").val("")
            $("input[name=startStr]").val("")
            $("input[name=endStr]").val("")
        }else{
            $("input[name=splitStr]").val(",")
            $("input[name=startStr]").val("")
            $("input[name=endStr]").val("")
        }
    });

});


function editTextarea(dom){
    var url = "editTextArea.html?|"+dom;
     layer.open({
        type:2,
        title:"<i class='layui-icon layui-icon-note'></i>&nbsp;数据集Sql",
        content:url,
         area: ['600px', '400px']
     })
}